<template>
  <div class="role-alloc-resource">
    <el-card class="box-card" v-for="category in  roleSourceData" :key="category.sourceId">
      <div slot="header" class="clearfix">
        <el-checkbox :indeterminate="category.isIndeterminate" v-model="category.selected"
                     @change="handleCheckAllChange(category)">{{ category.sourceName }}
        </el-checkbox>
        <!--        <div style="margin: 15px 0;"></div>-->
      </div>
      <el-checkbox-group v-model="category.checkResourceIds" @change="handleCheckedResourceChange(category)">
        <el-row>
          <el-col :span="8" v-for="resource in category.childrentVos" :key="resource.limitId">
            <el-checkbox :label="resource.limitId" style="padding: 7px 0px">{{ resource.limitName }}</el-checkbox>
          </el-col>
        </el-row>

      </el-checkbox-group>
    </el-card>
    <div class="foot">
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="onClear">清空</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<!--分配资源-->
<script>
//资源分配
import {getAllRoleResourceLimitLists} from "@/api/interfaceLimit/interfacelimit";
import {setRoleSource} from "@/api/roles/roles";


export default {
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  name: "RoleAllocResource",
  data() {
    return {
      roleSourceData: [],
      checkAll: false,
      notSelect:[]
    };
  },
  created() {
    this.LoadRoleSources()
  },
  methods: {
    //获取角色拥有的资源
    LoadRoleSources() {
      console.log("角色id::::", this.roleId);
      const data = {
        roleId: this.roleId
      }
      getAllRoleResourceLimitLists(data).then(res => {
        if (res.data.code === '200') {
          //对数据解构操作
          this.roleSourceData = res.data.data.map((category) => {
            let {sourceId, sourceName, childrentVos, selected} = category
            const checkResourceIds = []//记录当前类别下被选中的资源id
            const allResourceIds = []//记录当前类别下所有的资源id
            //如果没有值就返回undefined,有？
            childrentVos = childrentVos?.map((resource) => {
              const {limitId, limitName, selected} = resource;
              //把当前类别下被选中的资源id存储
              // if (selected == true) {
              //   checkResourceIds.push(limitId)
              // }
              //断路写法
              selected && checkResourceIds.push(limitId)
              //当前类别下所有的资源id存储
              allResourceIds.push(limitId)
              return {limitId, limitName, selected}
            })
            //表示类别是否减号状态
            const isIndeterminate = checkResourceIds.length > 0 && checkResourceIds.length < allResourceIds.length
            //菜单的选中状态
            selected = checkResourceIds.length === allResourceIds.length
            return {
              sourceId, sourceName, childrentVos, selected,
              //添加自定义属性
              checkResourceIds, allResourceIds, isIndeterminate
            }
            //sort方法暂时不理解
          }).sort((c1, c2) => c1.limitId - c2.limitId);
          console.log("资源角色数据列表:::::", res);
          this.$message.success('获取角色资源数据成功!')
        } else {
          this.$message.error('获取角色资源数据失败!')
        }
      })
    },
    //全选
    handleCheckAllChange(category) {
      category.checkResourceIds = category.selected ? category.allResourceIds : [];
      category.isIndeterminate = false;
    },
    //单选
    handleCheckedResourceChange(category) {
      console.log("单选：：：",category);
      //当前类别选中的个数
      let checkedCount = category.checkResourceIds.length;
      //当前类别下所有的个数
      let totalCount = category.allResourceIds.length;
      //是否把当前类别全选
      category.selected = checkedCount === totalCount;
      //是否展示全选有减去的符号
      category.isIndeterminate = checkedCount > 0 && checkedCount < totalCount;
    },
    //返回
    handleBack() {
      this.$router.push({name: 'roles'})
    },
    //清空所有类别
    onClear() {
      this.roleSourceData.forEach((category) => {
        category.checkResourceIds = []
        category.selected = false
        category.isIndeterminate = false
      })
    },
    //保存
    onSave() {
      const {roleId, roleSourceData} = this;
      //category是数组中的对象,每次遍历的
      //res的初始值是[]
      //reduce 一个回调函数和一个初始值（这里是 []，即空数组）
      const resourceIdList = roleSourceData.reduce((res, category) => {
        return res.concat(category.checkResourceIds)
      }, [])
      const data = {
        roleId: roleId,
        limitIds: resourceIdList
      }
      setRoleSource(data).then(res => {
        console.log("角色分配资源::::",res);
        if (res.data.code === '200') {
          this.$message.success('角色分配资源成功!')
          this.$router.push({name:'roles'})
        } else {
          this.$message.error('角色分配资源失败!')
        }
      })
    }
  }
}
</script>


<style scoped>
.foot-btn {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-card {
  margin-bottom: 20px;
}
</style>
